#include "history.h"
#include "ui_history.h"

History::History(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::History)
{
    ui->setupUi(this);
    ui->m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    m_db.setDatabaseName("test.db");
    if(!m_db.open())
    {
        qDebug() << m_db.lastError();
    }
    m_query = new QSqlQuery(m_db);

    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&History::updatetableInfo);
    timer->start(2000);

}

History::~History()
{
    delete ui;
}


void History::updatetableInfo()
{
    double temp;
    int humi,i = 0;
    QString time;
    QString sql = "DELETE FROM logs WHERE humi = 0;";
    if(!m_query->exec(sql))
    {
        qDebug() << "DELECT:" <<m_query->lastError();
    }
    sql = "SELECT * FROM logs;";
    if(!m_query->exec(sql))
    {
        qDebug() << "SELECT:" <<m_query->lastError();
    }
    while(m_query->next())
    {
        temp = m_query->value("temp").toDouble();
        QTableWidgetItem* item_temp = new QTableWidgetItem(QString::number(temp));
        ui->m_table->setItem(i,0,item_temp);
        humi = m_query->value("humi").toInt();
        QTableWidgetItem* item_humi = new QTableWidgetItem(QString::number(humi));
        ui->m_table->setItem(i,1,item_humi);
        time = m_query->value("time").toString();
        QTableWidgetItem* item_time = new QTableWidgetItem(time);
        ui->m_table->setItem(i,2,item_time);
        i++;
    }
}

void History::receiveDBSlots(QSqlDatabase db)
{
    m_db = db;
    qDebug() <<"接收成功";
}

void History::on_pushButton_clicked()
{
    ui->m_table->clear();
    QStringList columnNames;
    columnNames << "温度" << "湿度" << "时间";
    ui->m_table->setHorizontalHeaderLabels(columnNames);
    timer->stop();
}

void History::on_m_updat_clicked()
{
    QString sql = "DELETE FROM logs;";
    if (!m_query->exec(sql)) {
        qDebug() << "DELETE FROM logs:" << m_query->lastError();
    }
    ui->m_table->clear();
    QStringList columnNames;
    columnNames << "温度" << "湿度" << "时间";
    ui->m_table->setHorizontalHeaderLabels(columnNames);
}
